<?php

namespace App\Services;

use App\Models\File as FileMdl;

use Illuminate\Support\Facades\Storage;
use Exception;

class UploaderService
{
    /**
     * 上传文件
     */
    public static function upload($request)
    {
        $param = $request->input();
        if (!empty($param['total_count']) && !empty($param['total_count'])) {
            if (!empty($param['multi']) && $param['multi'] == 'true') {
                if ($param['total_count'] - $param['count'] <= 0) {
                    return response()->json(['code' => 0, 'msg' => '最多上传' . $param['total_count'] . '张']);
                }
            }
        }

        $folder = $param['folder'] ?? 'default';
        $field = $param['field'] ?? 'file';

        $config = Config::getUploadSetting();
        $storage = $config['storage'] ?? 'local';
        if ($request->get('place')) {
            $storage = $request->get('place') ?? 'local';
        }

        try {
            $file = $request->file($field);
            // 验证上传文件是否有效
            if (!$file->isValid()) {
                return response()->json(['code' => -1, 'msg' => '无效的文件']);
            }
            $mimetypes = $config['mimetype'] ?? [];
            //$max_filesizes = $config['max_filesizes'] ?? [];
            //$fileexts = $config['fileexts'] ?? [];
            //$file_ext  = $file->extension();
            $file_ori_name = $file->getClientOriginalName();
            $file_ext = strtolower($file->getClientOriginalExtension());
            if (empty($file_ext)) {
                return response()->json(['code' => 0, 'msg' => '上传的文件格式不允许']);
            }
            $file_type = FileService::typeJudge($file_ext);
            if (!in_array($file_type, ['image', 'video', 'audio'])) {
                $file_type = 'file';
            }
            $file_size = $file->getSize(); // 单位：字节
            // 验证
            if ($mimetypes && isset($mimetypes[$file_type])) {
                $max_filesize = $mimetypes[$file_type]['max_filesize'];
                $fileexts = $mimetypes[$file_type]['extensions'];
                $fileexts_arr = explode(',', $fileexts);
                if (!in_array($file_ext, $fileexts_arr)) {
                    return response()->json(['code' => 0, 'msg' => '上传的文件格式不允许，允许格式：' . $fileexts]);
                }
                $max_filesize_byte = $max_filesize * 1024; // 转为字节
                if ($file_size > $max_filesize_byte) {
                    return response()->json(['code' => 0, 'msg' => '上传的文件大小不允许，允许大小：' . $max_filesize . ' KB']);
                }
            }

            if ($storage == 'local') {
                // 上传到本地
                //$originalName = $file->getClientOriginalName(); // 文件原名
                $ext = $file->getClientOriginalExtension(); // 扩展名
                $realPath = $file->getRealPath(); // 临时文件的绝对路径
                //$type = $file->getClientMimeType(); // image/jpeg
                //$size = $file->getClientSize(); // 文件的大小

                $folderName = $folder . '/' . date('Y-m') . '/' . date('d');
                $filename = $folderName . '/' . uniqid() . '.' . $ext;
                // 这里的uploads是配置文件的名称
                $result = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
                if ($result) {
                    $filePath = $filename;
                    $fullFilePath = asset(config('path.upload_path') . $filePath);
                } else {
                    return response()->json(['code' => 0, 'msg' => '上传失败']);
                }
            } elseif ($storage == 'qiniu') {
                // 上传到七牛
                $qiniu = new Qiniu();
                $result = $qiniu->uploadFile($_FILES[$field]);
                if ($result['code'] == 1) {
                    $filePath = $qiniu->url . $result['key'];
                    $fullFilePath = $filePath;
                } else {
                    return response()->json(['code' => 0, 'msg' => $result['msg']]);
                }
            } elseif ($storage == 'tencentyun') {
                // 上传到腾讯云
                $qcloud = new Qcloud();
                $result = $qcloud->uploadFile($_FILES[$field]);
                if ($result['code'] == 1) {
                    $filePath = $qcloud->url . $result['key'];
                    $fullFilePath = $filePath;
                } else {
                    return response()->json(['code' => 0, 'msg' => '', 'result' => $result]);
                }
            } else {
                return response()->json(['code' => -1, 'msg' => '不支持的上传空间']);
            }

            // 插入uploads表记录
            $fileData = [
                //'id' => get_UUID(),
                'created_at' => time(),
                'file_name' => $file_ori_name,
                'file_url' => $filePath,
                'file_type' => $file_type,
                'file_size' => $file_size,
                'file_ext' => $file_ext,
                'folder' => $folder,
                'storage' => $storage,
                'status' => 0
            ];
            FileMdl::insert($fileData);
            return response()->json([
                'code' => 1,
                'msg' => '上传成功',
                'filename' => $file_ori_name,
                'filesize' => $file_size,
                'filepath' => $filePath,
                'full_filepath' => $fullFilePath,
                'result' => $result
            ]);
        } catch (Exception $e) {
            return response()->json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }
}
